<?php

require_once 'html-extractor.php';
require_once 'file_php.php';
require_once 'Item.php';
require_once 'Utils.php';

$debug = false;
$todayUrl = "http://www.todayonhistory.com/";

// global key string

/**
 * remove tail's content that are unnecessary right now
 */
function removeTail($content) {
	// remove tail
	$kTailIdentifier = "</ul>";
	if (false != ($pos = strpos ( $content, $kTailIdentifier ))) {
		$content = substr ( $content, 0, $pos );
	}
	return $content;
}

/**
 * return item's array
 *
 * @param unknown_type $content        	
 */
function getItemArray($content, $date) {
	global $debug;
	$content = removeTail ( $content );
	global $todayUrl;
	// get the first history event
	$kItemEnd = "</li>";
	$items = array ();
	while ( false != ($pos = strpos ( $content, $kItemEnd )) ) {
		$item = substr ( $content, 0, $pos );
		if ($debug) {
			echo "item:" . $item . '<br/>';
		}
		if (false == $item) {
			if ($debug) {
				echo "no more content:" . '<br/>';
			}
			return false;
		}
		$value = getItem ( $item, $date );
		if (false != $value) {
			$link = $todayUrl . $value->link ();
			$value->setLink ( $link );
			// image heigth and width
			if ($debug) {
				echo "image url: " . $value->image () . '<br/>';
			}
			$size = getimagesize ( $value->image (), $imageinfo );
			$value->setWidth ( $size [0] );
			$value->setHeight ( $size [1] );
			if ($debug) {
				echo "width: " . $imageinfo [0] . '<br/>';
			}
			// get link's main content
			$linkText = HTMLExtractor::getUrlMainContent ( $link, 200, 1 );
			if (strlen ( $linkText ) != 0) {
				$value->setDescription ( HTMLExtractor::convertToUTF8 ( $linkText ) );
				array_push ( $items, $value );
			}
		}
		// get next content
		$content = substr ( $content, $pos + 1, strlen ( $content ) - $pos - 1 );
		if ($debug) {
			echo "next content:" . $content . '<br/>';
		}
	}
	return $items;
}

/**
 *
 * @param unknown_type $item        	
 * @return Item false when failure
 */
function getItem($item, $date) {
	global $debug;
	global $todayUrl;
	// get title and link
	$title = "";
	$link = "";
	if (preg_match ( '/title="([\s\S]*)"/m', $item, $regs )) {
		$title = $regs [1];
		if ($debug) {
			echo "title:" . $title . '<br/>';
		}
	} else {
		if ($debug) {
			echo "no title:" . '<br/>';
		}
		return false;
	}
	
	if (preg_match ( '/href="([^=]*)"/m', $item, $regs )) {
		$link = $regs [1];
		if ($debug) {
			echo "link:" . $link . '<br/>';
		}
	} else {
		if ($debug) {
			echo "no link:" . '<br/>';
		}
		return false;
	}
	// get image
	$images = array ();
	$image = "";
	if (preg_match ( '/rel="([^=]*)"/m', $item, $regs )) {
		if ($regs [1] [0] == '/') {
			$image = $todayUrl . substr ( $regs [1], 1, strlen ( $regs [1] ) - 1 );
		} else if (false == strstr ( $regs [1], "http" )) {
			$image = $todayUrl . $regs [1];
		} else {
			$image = $regs [1];
		}
		if ($debug) {
			echo "image:" . $image . '<br/>';
		}
	} else {
		if ($debug) {
			echo "no image:" . '<br/>';
		}
		return false;
	}
	// array_push ( $images, $image );
	return new Item ( $title, $image, $link, $date, "" );
}
function getHistoryEvent() {
	global $todayUrl;
	$date_format = "n-j";
	// write to file
	$dates = array (
			Utils::getYesterday ( $date_format ),
			Utils::getToday ( $date_format ),
			Utils::getTommorrow ( $date_format ) 
	);
	// if true, good; if false, zip creation failed
	$zipFile = Utils::getDataPath () . 'textevents.zip';
	
	// file updated
	if (file_exists ( $zipFile ) && (Utils::getTime ( $date_format, filemtime ( $zipFile ) ) === Utils::getToday ( $date_format ))) {
		echo "file zipped" . '<br/>';
		return;
	}
	
	$files_to_zip = array ();
	
	foreach ( $dates as $date ) {
		$filename = Utils::getDataPath () . $date . '.xml';
		if (file_exists ( $filename )) {
			$files_to_zip [] = $filename;
			continue;
		}
		
		$dateUrl = $todayUrl . $date;
		$dateUrl = str_replace ( '-', '\\', $dateUrl );
		$htmlContent = HTMLExtractor::getUrlHtml ( $dateUrl );
		// match content segment
		if (preg_match ( '%<li[\s]class="(gong|nong)[\s\S]*</li>%', $htmlContent, $regs )) {
			$result = $regs [0];
		} else {
			$result = "";
		}
		$file = new file_php ( $filename );
		$file->open ();
		$file->write ( "\xEF\xBB\xBF" );
		$file->writeutf8 ( Utils::getRssHeader () );
		
		// match item by item
		$items = getItemArray ( $result, $date );
		foreach ( $items as $value ) {
			$file->write ( $value->getRss () );
		}
		$file->write ( Utils::getRssTail () );
		$file->close ();
		
		// add to zip
		$files_to_zip [] = $filename;
	}
	
	file_php::create_zip ( $files_to_zip, $zipFile, true );
}
function getRecentEventJson() {
	global $todayUrl, $debug;
	$date_format = "n-j";
	// write to file
	$dates = array (
			Utils::getYesterday ( $date_format ),
			Utils::getToday ( $date_format ),
			Utils::getTommorrow ( $date_format ) 
	);
	
	$zipFlag = true; // whether zip files
	$zipFile = Utils::getDataPath () . 'textevents.zip';
	
	// file updated
	if ($zipFlag && file_exists ( $zipFile ) && (Utils::getTime ( $date_format, filemtime ( $zipFile ) ) === Utils::getToday ( $date_format ))) {
		echo "file zipped" . '<br/>';
		return;
	}
	
	$files_to_zip = array ();
	
	foreach ( $dates as $date ) {
		$filename = Utils::getDataPath () . $date . '.json';
		if (file_exists ( $filename )) {
			if ($zipFlag) {
				$files_to_zip [] = $filename;
			}
			continue;
		}
		
		$dateUrl = $todayUrl . $date;
		$dateUrl = str_replace ( '-', '\\', $dateUrl );
		$htmlContent = HTMLExtractor::getUrlHtml ( $dateUrl );
		// match content segment
		if (preg_match ( '%<li[\s]class="(gong|nong)[\s\S]*</li>%', $htmlContent, $regs )) {
			$result = $regs [0];
		} else {
			$result = "";
		}
		if ($debug) {
			echo "result: " . $result . '<br/>';
		}
		// match item by item
		$items = getItemArray ( $result, $date );
		
		if (! $debug) {
			file_php::writeJson ( $filename, json_encode ( $items ) );
		}
		
		if ($zipFlag) {
			// add to zip
			$files_to_zip [] = $filename;
		}
	}
	
	if ($zipFlag) {
		file_php::create_zip ( $files_to_zip, $zipFile, true );
	}
}
function getHistoryEventJson() {
	global $todayUrl, $debug;
	$date_format = "n-j";
	$zipFlag = false; // whether zip files
	$zipFile = Utils::getDataPath () . 'textevents.zip';
	
	// file updated
	if ($zipFlag && file_exists ( $zipFile ) && (Utils::getTime ( $date_format, filemtime ( $zipFile ) ) === Utils::getToday ( $date_format ))) {
		echo "file zipped" . '<br/>';
		return;
	}
	
	$files_to_zip = array ();
	
	// begin:get whole year's data
	for($i = 0; $i <= 365; $i ++) {
		$date = Utils::getDate ( $date_format, $i );
		// end
		if (false == $date) {
			echo "time exception,break" . "<br/>";
			break;
		}
		$filename = Utils::getDataPath () . $date . '.json';
		if (file_exists ( $filename )) {
			if ($zipFlag) {
				$files_to_zip [] = $filename;
			}
			continue;
		}
		
		$dateUrl = $todayUrl . $date;
		$dateUrl = str_replace ( '-', '\\', $dateUrl );
		$htmlContent = HTMLExtractor::getUrlHtml ( $dateUrl );
		// match content segment
		if (preg_match ( '%<li[\s]class="(gong|nong)[\s\S]*</li>%', $htmlContent, $regs )) {
			$result = $regs [0];
		} else {
			$result = "";
		}
		if ($debug) {
			echo "result: " . $result . '<br/>';
		}
		// match item by item
		$items = getItemArray ( $result, $date );
		
		if (! $debug) {
			file_php::writeJson ( $filename, json_encode ( $items ) );
		}
		
		echo "filename: " .$filename. "<br/>";
		
		if ($zipFlag) {
			// add to zip
			$files_to_zip [] = $filename;
		}
	}
	
	if ($zipFlag) {
		file_php::create_zip ( $files_to_zip, $zipFile, true );
	}
}

// run this script
set_time_limit ( 0 );
$kDefaultUrl = "http://www.idreems.com/example.php?php/todayinhistory/data/textevents.zip";

$needle = "textevents";
$request = $_GET ["channel"];
if (false == $request) {
	getHistoryEventJson ();
} else if (false != strstr ( $request, $needle )) {
	if ($debug) {
		echo "zip right now" . "<br/>";
	}
	getRecentEventJson ();
	header ( "location:" . $kDefaultUrl );
	if ($debug) {
		echo $kDefaultUrl . '<br/>';
	}
} else {
	print ("<html><body>Bad request.</body></html>") ;
}